import { useState } from "react";
import {
  Card,
  Pagination,
  Tag,
  Row,
  Col,
  Spin,
  Button,
  Avatar,
  Image,
  Modal,
  Popconfirm,
  message,
} from "antd";
import {
  HeartFilled,
  HeartOutlined,
  EditOutlined,
  DeleteOutlined,
  WarningFilled,
  FileWordFilled,
  WarningOutlined,
  DeleteFilled,
  SettingFilled,
} from "@ant-design/icons";
import "./UserExplore.css"; // 自定义样式文件
import { httpPost, httpPostDownload } from "@utils/HttpUtil";
import { getPreviewUrl } from "@utils/WeStudyUtil";
import SelectKnowledgeTree from "src/common/component/SelectKnowledgeTree";
import { getToday } from "@utils/TimeUtil";
const { Meta } = Card;

const UserExplore = () => {
  // 初始化卡片数据
  const page = 0; // 初始页码
  const pageSize = 6; // 每页显示的卡片数量

  // 获取卡片数据的函数
  const getCardData = (page: any, pageSize:any, tags: any) => {
    return httpPost("/problem/getPageProblemList", {
      page: page,
      pageSize: pageSize,
      tags: tags,
    }).data;
  };

  // 状态管理
  const initData = getCardData(page, pageSize, []);
  const [cards, setCards] = useState(initData.items);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    total: initData.total,
  });
  // 选中的标签

  const [selectedTags, setSelectedTags] = useState<any>([]);
  const [favorites, setFavorites] = useState(() => {
    const saved = localStorage.getItem("favorites");
    return saved ? JSON.parse(saved) : [];
  });
  const [mistakes, setMistakes] = useState(() => {
    const saved = localStorage.getItem("mistakes");
    return saved ? JSON.parse(saved) : [];
  });

  // 可用筛选标签（示例）
  var filterTags = httpPost("/userDetail/getUserTagList", {}).data || [];
  const [tagIds, setTagIds] = useState<any>(filterTags);
  const filterTagList =
    httpPost("/knowledge/getKnowledgeList", { idList: filterTags })
      .data || [];
  const [tagList, setTagList] = useState(filterTagList);

  const refreshCardData = (selectedTags: any) => {
    // 根据选中的标签获取卡片数据
    setLoading(true);
    var data = getCardData(0, pageSize, selectedTags);
    setCards(data.items);
    setPagination({
      current: 0,
      pageSize: pageSize,
      total: data.total,
    });
    setLoading(false);
  };

  // 标签筛选处理
  const handleTagSelect = (tag: any) => {
    var newSelectedTags = [...selectedTags];
    if (selectedTags.includes(tag.id)) {
      newSelectedTags = newSelectedTags.filter((t: any) => t !== tag.id);
    } else {
      newSelectedTags.push(tag.id);
    }
    setSelectedTags(newSelectedTags);
    refreshCardData(newSelectedTags);
  };

  // 收藏处理
  const toggleFavorite = (id: any) => {
    httpPost("/userDetail/markUserProblemDetail", {
      problemId: id,
      type: "favorite"
    });
    const newFavorites = favorites.includes(id)
      ? favorites.filter((favId: any) => favId !== id)
      : [...favorites, id];

    setFavorites(newFavorites);
    localStorage.setItem("favorites", JSON.stringify(newFavorites));

    setCards((prev: any) =>
      prev.map((card: any) =>
        card.id === id ? { ...card, isFavorite: !card.isFavorite } : card
      )
    );
  };

  //错题标记
  const toggleMistake = (id:any) =>{
    httpPost("/userDetail/markUserProblemDetail", {
      problemId: id,
      type: "mistake"
    });
    const newMistakes = mistakes.includes(id)
      ? mistakes.filter((mistakeId: any) => mistakeId !== id)
      : [...mistakes, id];

    setMistakes(newMistakes);
    localStorage.setItem("mistakes", JSON.stringify(newMistakes));

    setCards((prev: any) =>
      prev.map((card: any) =>
        card.id === id ? { ...card, isMistake: !card.isMistake } : card
      )
    );
  }

  // 分页处理
  const handlePaginationChange = (page: any, pageSize: any) => {
    setLoading(true);
    var data = getCardData(page, pageSize, selectedTags);
    setCards(data.items);
    setPagination({ current: page, pageSize, total: pagination.total });
    setLoading(false);
  };

  //自定义筛选项的模态框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const selectKnowledgeTree = (value: any) => {
    console.log(value);
    setTagIds(value);
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
    // 保存选项逻辑
    const filterTags =
      httpPost("/knowledge/getKnowledgeList", { idList: tagIds }).data || [];
    setTagList(filterTags);
    httpPost("/userDetail/updateUserTagList", {tags: tagIds});
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 渲染题目编辑组件
  const [selectedProblem, setSelectedProblem] = useState<any>({
    tags: [],
  });
  const [itemTagIds, setItemTagIds] = useState<any>([]);
  const selectItemKnowledgeTree = (value: any) => {
    console.log(value);
    setItemTagIds(value);
  };
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

  const showEditModal = (card: any) => {
    console.log(card);
    setSelectedProblem(card);
    setIsEditModalOpen(true);
  };

  const handleEditOk = () => {
    setIsEditModalOpen(false);
    // 修改题目逻辑
    httpPost("/problemKnowledge/batchAddByProblemId", {
      problemId: selectedProblem.id,
      knowledgeIdList: itemTagIds,
    });
    //刷新卡片数据
    refreshCardData(selectedTags);
  };

  const handleEditCancel = () => {
    setIsEditModalOpen(false);
  };

  return (
    <div className="card-browser">
      {/* 筛选标签区 【必须优化】 */}
      <div className="filter-section">
        {tagList.map((tag: any) => (
          <Tag.CheckableTag
            key={tag.id}
            checked={selectedTags.includes(tag.id)}
            onChange={() => handleTagSelect(tag)}
            className={`filter-tag ${
              selectedTags.includes(tag.name) ? "active" : ""
            }`}
          >
            {tag.name}
          </Tag.CheckableTag>
        ))}
        <div>
          <SettingFilled style={{ color: "#4e7ca1", fontSize: 18}} />
          <Button
            type="link"
            onClick={showModal}
            style={{ paddingLeft: 0 }}
          >
            自定义筛选项
          </Button>
        </div>
        <Modal
          title={"自定义筛选项"}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          width={1200}
          style={{ margin: "auto", width: "1000px" }}
        >
          <>
            <div style={{ height: 20 }}></div>
            <SelectKnowledgeTree
              onChange={selectKnowledgeTree}
              max={20}
              value={tagIds}
            />
            <div style={{ height: 200 }}></div>
          </>
        </Modal>

        <div>
          <DeleteFilled style={{ color: "#4e7ca1", fontSize: 18}} />
          <Button
            type="link"
            onClick={() => {
              setSelectedTags([]);
              refreshCardData([]);
            }}
            style={{ paddingLeft: 0 }}
          >
            清除选择
          </Button>
        </div>

        <Popconfirm
          title="导出Word"
          description="确定导出Word吗?范围为筛选之后的最多100道题目"
          onConfirm={() => {
            message.success("正在导出Word");
            var data = getCardData(0, 100, selectedTags);
            httpPostDownload(
              "/fileRecord/exportProblemWord",
              getToday() + "题目.docx",
              {
                problemList: data.items,
              }
            );
            httpPostDownload(
              "/fileRecord/exportExplainWord",
              getToday() + "解析.docx",
              {
                problemList: data.items,
              }
            );
            // httpPostDownload(
            //   "/fileRecord/exportProblemExplainWord",
            //   getToday() + "题目解析.docx",
            //   {
            //     problemList: data.items,
            //   }
            // );
          }}
          onCancel={() => {}}
          okText="确定"
          cancelText="取消"
        >
          <FileWordFilled style={{ color: "#4e7ca1", fontSize: 18 }} />
          <Button type="link" onClick={() => {}} style={{ padding: 1 }}>
            导出Word
          </Button>
        </Popconfirm>

        <Modal
          title={"修改题目知识点"}
          open={isEditModalOpen}
          onOk={handleEditOk}
          onCancel={handleEditCancel}
          destroyOnClose={true}
          width={1200}
          style={{ margin: "auto", width: "1000px" }}
        >
          <>
            <div style={{ height: 20 }}></div>
            <SelectKnowledgeTree
              onChange={selectItemKnowledgeTree}
              max={20}
              value={selectedProblem.tags.map((tag: any) => tag.id)}
            />
            <div style={{ height: 200 }}></div>
          </>
        </Modal>
      </div>

      {/* 卡片展示区 */}
      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {cards.map((card: any) => (
            <Col key={card.id} lg={8}>
              <Card
                className="custom-card"
                style={{ height: "250px" }}
                cover={
                  <Image.PreviewGroup items={card.images}>
                    <Image
                      src={card.images[0]}
                      style={{ objectFit: "contain" }}
                      height={90}
                    />
                  </Image.PreviewGroup>
                }
                actions={[
                  <div onClick={() => toggleFavorite(card.id)}>
                    {card.isFavorite ? (
                      <HeartFilled style={{ color: "#ff4d4f" }} />
                    ) : (
                      <HeartOutlined />
                    )}
                  </div>,
                  <div onClick={() => toggleMistake(card.id)}>
                    {card.isMistake ? (
                      <WarningFilled style={{ color: "#ff4d4f" }} />
                    ) : (
                      <WarningOutlined />
                    )}
                  </div>,
                  <EditOutlined
                    key="edit"
                    onClick={() => showEditModal(card)}
                  />,
                  <Popconfirm
                    title="删除题目"
                    description="确定删除题目吗?"
                    onConfirm={() => {
                      httpPost("/problem/deleteProblem", {
                        problemId: card.id,
                      });
                      message.success("题目删除成功！");
                      refreshCardData(selectedTags);
                    }}
                    onCancel={() => {}}
                    okText="确定"
                    cancelText="取消"
                  >
                    <DeleteOutlined key="delete" />
                  </Popconfirm>,
                ]}
              >
                <Meta
                  avatar={
                    <Avatar
                      src={getPreviewUrl() + "4e80d97a462846db95b0c116e342a31f"}
                    />
                  }
                  title={card.title}
                  description={
                    <div className="card-tags">
                      {card.tags.map((knowledge: any) => (
                        <Tag
                          style={{ marginBottom: "1px", marginRight: "3px" }}
                          key={knowledge.id}
                          color={knowledge.color || "blue"}
                        >
                          {knowledge.name}
                        </Tag>
                      ))}
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Spin>

      {/* 分页控件 */}
      <div className="pagination-container">
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          onChange={handlePaginationChange}
          showSizeChanger={false}
          pageSizeOptions={["12", "24", "36"]}
          showTotal={(total) => `共 ${total} 个`}
        />
      </div>
    </div>
  );
};

export default UserExplore;
